#pragma once

// 将服务器处理功能进行模块化
#include "protocol.hpp"
#include <cassert>

enum
{
    DIV_Zero = 1,
    MOD_Zero
};

class ServerCal
{
public:
    ServerCal()
    {
    }

    Response CalculatorHelpor(Request &req)
    {
        Response rsp(0, 0);
        switch (req.op)
        {
        case '+':
            rsp.result = req.x + req.y;
            break;

        case '-':
            rsp.result = req.x - req.y;
            break;

        case '*':
            rsp.result = req.x * req.y;
            break;

        case '/':
        {
            if (req.x == 0 | req.y == 0)
            {
                rsp.code = DIV_Zero;
            }
            else
            {
                rsp.result = req.x / req.y;
            }
        }
        break;

        case '%':
        {
            if (req.x == 0 | req.y == 0)
            {
                rsp.code = DIV_Zero;
            }
            else
            {
                rsp.result = req.x + req.y;
            }
        }
        break;

        default:
            std::cout << "op not exist..." << std::endl;
            break;
        }

        return rsp;
    }

    std::string Calculator(std::string &pakeage)
    {
        std::string content;                //"7"\n"10 + 20"\n
        bool r = Decode(pakeage, &content); //"10 + 20"
        if (!r)
            return "";

        Request req;
        r = req.Deserialize(content); // x = 10 y = 20 op = +
        if (!r)
            return "";

        Response rsq = CalculatorHelpor(req); // result = 30 code = 0
        // 清空上一次的数据
        content = "";
        // 序列化
        r = rsq.serialize(&content); //"30 0"
        assert(r);                   // r为真继续走，r为假终止程序
        // 封装报头
        content = Encode(content); //"4"\n"10 0"\n

        return content;
    }
};